package ext.tianma.part.processors;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import wt.fc.Identified;
import wt.fc.IdentityHelper;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.collections.WTArrayList;
import wt.lifecycle.LifeCycleException;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.part.Source;
import wt.part.WTPart;
import wt.part.WTPartMasterIdentity;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;

import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.generic.erp.common.ExcelUtil;
import ext.tianma.part.PartWorkflowUtil;
import ext.tianma.part.imported.ImportedExcelUtil;

public class UpdatePartsAttributeProcessors extends DefaultObjectFormProcessor{
	//处理IBA属性集合
	private static List< String > list = new ArrayList<String>();
	private static final String D_VIEW = "Design";
	private static final String FILE_NAME = "checkUpdatePartAttribute.xlsx";
	
	static{
		//配置文件与ext.tianma.part.processors.UpdatePartsAttributeProcessors.class文件在同一路径下
		String filePath = UpdatePartsAttributeProcessors.class.getResource("").getPath() ;
		
		//BUG Fix，解决Linux下文件路径中windchill小写不能找到文件的BUG
		filePath = filePath.replaceAll("windchill", "Windchill") ;
		
		list = parseExcel( filePath + FILE_NAME );
		System.out.println("filePath====>>"+filePath);
	}

	@Override
	public FormResult doOperation( NmCommandBean nmCommandBean , List list )throws WTException {
		FormResult formresult = new FormResult();
		
		HttpServletRequest request = nmCommandBean.getRequest();
		
		if( request != null ){
			String[] parameter = request.getParameterValues( "fileUrl" );
			
			if( parameter == null ){
				 return formresult;
			 }
			 
			 String textName = parameter[0];
			 
			 if( textName != null ){
				 //判断是否为Excel文件类型
				 if( !textName.endsWith(".xls") && !textName.endsWith( ".xlsx" ) ){
					 throw new WTException("选择的文件必须是Excel格式的文件");
				 }
			 }
			 
			 File file = (File) request.getAttribute("fileUrl");
			 
			 if( file != null ){
				 String fileNumber = file.getAbsolutePath(); 
				 
				 if( fileNumber != null ){
					 FileInputStream fis = null;
					 Workbook wb = null;
					 boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
					 StringBuffer strBuf = new StringBuffer();
					 try {
						fis = new FileInputStream(fileNumber);
						//根据Excel文件的格式判断文件的解释方式为03或07（解析Excel兼容性）
						if( textName.endsWith(".xls") ){
							wb = new HSSFWorkbook( fis );
						}else if( textName.endsWith( ".xlsx" ) ){
							wb = new XSSFWorkbook( fis );
						}
						
						
						if( wb != null ){
							updatePartsAttribute( wb , strBuf );
						}						
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}finally{									
						SessionServerHelper.manager.setAccessEnforced( flag );
					}
					
					if( strBuf.length() > 0 ){
						strBuf.append( "需要修改对象视图不存在或检出无法进行属性更新。" );
						System.out.println( "Update Part Error : " + strBuf.toString() );
						formresult.addFeedbackMessage( new  FeedbackMessage(
								FeedbackType.FAILURE, null, strBuf.toString() , null, new String[] {} ) );
					}else{
						formresult.addFeedbackMessage( new  FeedbackMessage(
								FeedbackType.SUCCESS, null, "物料更新成功" , null, new String[] {} ) );
					}
				 }
			 }
		}

		return formresult;
	}
	
	
	/**
	 * 批量修改物料属性（1）
	 * @param wb
	 * @param outPartList
	 * @throws WTException
	 * @throws RemoteException 
	 */
	private void updatePartsAttribute( Workbook wb , StringBuffer strBuf ) throws WTException, RemoteException {
		if( wb == null ){
			return;
		}
		
		Sheet sheet = wb.getSheetAt(0); 
		
		if( sheet != null ){
			Hashtable< Integer , String > titleTable = getTitleHashtble( sheet.getRow( 1 ) );
			int count = sheet.getLastRowNum()+1;
			
			for( int i = 2 ; i < count ; i++ ){
				Row row = sheet.getRow( i );
				
				if( row != null ){
					System.out.println( "Debug   start   row : " + row.getRowNum() );
					updatePartsAttribute( row , titleTable , strBuf );
					System.out.println( "Debug   stop   row : " + row.getRowNum() );
				}
			}
		}			
	}
	
	/**
	 * 批量修改物料属性（2）
	 * @param row
	 * @param titleTable
	 * @param outPartList
	 * @throws WTException
	 * @throws RemoteException 
	 */
	private void updatePartsAttribute( Row row , Hashtable<Integer, String> titleTable , StringBuffer strBuf ) throws WTException, RemoteException {
		if( row == null ){
			return;
		}
		
		//先获取零部件编号
		String number = ImportedExcelUtil.getCellValueAsString( row.getCell( 0 ) , true );
		System.out.println("number====>>>"+number);
		if( number != null && !number.trim().isEmpty() ){
			WTPart part = CoreUtil.getWTPartByNumberAndView( number , D_VIEW );
			System.out.println("part===>>>"+part.getName());
			if( part != null ){
				//需要修改IBA集合
				Hashtable hashtable = new Hashtable();
				System.out.println("titleTable.size()===>>"+titleTable.size());
				System.out.println("===>>>attribu1teName==>>>"+titleTable.get(2));
				System.out.println("===>>>attribu2teName==>>>"+titleTable.get(3));
				System.out.println("===>>>attribu3teName==>>>"+titleTable.get(4));
				System.out.println("===>>>attribu4teName==>>>"+titleTable.get(5));
				for( int i = 2 ; i <= titleTable.size()+1 ; i++ ){

					//获取IBA属性内部名称
					String attributeName = titleTable.get( i );
					System.out.println("attributeName===>>"+attributeName);
					//获取IBA属性值
					String attributeValue = ImportedExcelUtil.getCellValueAsString( row.getCell( i ) , true );
					System.out.println("attributeValue===>>"+attributeValue);
					if( attributeValue == null || attributeValue.trim().isEmpty() ){
						continue;
					}
					
					if( attributeName.equals( "State" ) ){
						setPartAttribute( row , attributeName , attributeValue , strBuf );
						continue;
					}else if( attributeName.equals( "Source" ) ){
						setPartAttribute( row , attributeName , attributeValue , strBuf );
						continue;
					}else if( attributeName.equals( "name" ) ){
						if( WorkflowUtil.isObjectCheckedOut( part ) ){
							String str = strBuf+"";
							String dr = number+"("+D_VIEW+")";
							System.out.println("dr====>>>"+dr);
							if( str.trim().contains( dr ) ){
								return;
							}
							
							strBuf.append( dr );
							strBuf.append( "\n" );
							return;
						}
						
						setName( part , attributeValue );
						continue;
					}
					
					getUpdatePartsAttribute( attributeName , attributeValue , hashtable );						
				}
				
				System.out.println("hashtable===>>."+hashtable);
				if( hashtable == null || hashtable.size() == 0 ){
					return;
				}

				if( WorkflowUtil.isObjectCheckedOut( part ) ){
					String str = strBuf+"";
					String dr = number+"("+D_VIEW+")";
					if( str.trim().contains( dr ) ){
						return;
					}
					
					strBuf.append( dr );
					strBuf.append( "\n" );
					return;
				}
				
				part = CoreUtil.getWTPartByNumberAndView( part.getNumber() , part.getViewName() );
				
				part = (WTPart) CoreUtil.checkoutObject( part );
				
				IBAUtil.forceSetIBAValues( part ,  hashtable );
				
				CoreUtil.checkinObject( part , "物料属性更新完成");
			}else{
				String str = strBuf+"";
				String dr = number+"("+D_VIEW+")";
				if( str.trim().contains( dr ) ){
					return;
				}
				
				strBuf.append( dr );
				strBuf.append( "\n" );
			}
		}		
	}

	/**
	 * 获取需要修改的IBA属性集合
	 * @param attributeName
	 * @param attributeValue
	 * @param hashtable
	 */
	private void getUpdatePartsAttribute( String attributeName , String attributeValue , Hashtable hashtable ) {
		System.out.println("attributeName===>>"+attributeName+"attributeValue==>>"+attributeValue);
		if( attributeName == null || attributeValue == null || attributeName.trim().isEmpty() || attributeValue.trim().isEmpty() ){
			return;
		}
		
		hashtable.put( attributeName.trim() , attributeValue.trim() );

	}

	/**
	 * 获取零部件需要修改的属性名称
	 * @param row
	 * @return
	 * @throws WTException
	 */
	private Hashtable<Integer, String> getTitleHashtble( Row row ) throws WTException {
		Hashtable< Integer , String > hashtable = new Hashtable<Integer, String>();
		
		if( row == null ){
			throw new WTException( "批量修改的Excel的格式有误，无法获取需要修改属性的内部名称！" );
		}
		
		Iterator< Cell > iterator =  row.cellIterator();
		
		while( iterator.hasNext() ){
			Cell cell = iterator.next();
			
			if( cell != null ){				
				int cellColumnIndex = cell.getColumnIndex() ;
				String cellValue = ImportedExcelUtil.getCellValueAsString( cell , true );
				
				if( cellValue != null && !cellValue.trim().isEmpty() ){
					//判断IBA属性是否能修改
					if( list.contains( cellValue.trim() ) ){
						hashtable.put( cellColumnIndex , cellValue.trim() );
					}					
				}
			}
		}	
		return hashtable;
	}
	
	/**
	 * 设置物料状态（获取物料指定视图对象）
	 * @param row
	 * @param interiorValue
	 * @param value
	 * @throws WTException
	 */
	private void setPartAttribute( Row row , String attributeName , String attributeValue , StringBuffer strBuf ) throws WTException {
		if( row == null ){
			return;
		}
		//获取零部件编号
		String number = ImportedExcelUtil.getCellValueAsString( row.getCell( 0 ) , true );
		//获取零部件视图
		String view = ImportedExcelUtil.getCellValueAsString( row.getCell( 1 ) , true );
		
		if( number != null && view != null ){
			view = view.trim();
			number = number.trim();
			
			if( !number.isEmpty() && !view.isEmpty() ){
				//根据零部件指定视图来获取对象
				WTPart part = CoreUtil.getWTPartByNumberAndView( number , view );

				if( part != null && part.getViewName().equals( view ) ){
					
					if( WorkflowUtil.isObjectCheckedOut( part ) ){
						String str = strBuf+"";
						String dr = number+"("+view+")";
						if( str.trim().contains( dr ) ){
							return;
						}
						
						strBuf.append( dr );
						strBuf.append( "\n" );
						return;
					}
		
					if( attributeName.trim().contains( "State" ) ){
						setState( part , attributeValue );
					}else if( attributeName.trim().contains( "Source" ) ){
						setSource( part , attributeValue );
					}
				}else{
					String str = strBuf+"";
					String dr = number+"("+view+")";
					if( str.trim().contains( dr ) ){
						return;
					}
					
					strBuf.append( dr );
					strBuf.append( "\n" );
				}
			}
		}		
	}
	
	/**
	 * 设置物料状态
	 * @param part
	 * @param attributeValue
	 * @param logInfo
	 * @throws WTException
	 */
	public static void setState(WTPart part, String attributeValue ) throws WTException {
		if( attributeValue == null || attributeValue.trim().isEmpty() ){
			return ;
		}
		
		String start = part.getLifeCycleState().toString();
		
		if( start.equals( attributeValue ) ){
			return;
		}
		
		State state = State.toState(attributeValue.trim()) ;
		
		if( state != null ){
			try {
				WTArrayList partList = PartWorkflowUtil.getAllPartViews(part);// 获取所有视图
				
				int size = partList.size() ;
				for(int i = 0 ; i < size ; i++ ){
					Persistable persistable = partList.getPersistable(i) ;
					
					if( persistable != null && persistable instanceof WTPart ){
						WTPart partByView = ( WTPart ) persistable ;
						LifeCycleHelper.service.setLifeCycleState( partByView , state );
						System.out.println("sucessful===>>>");
					}
				}
				
				
			} catch (LifeCycleException e) {				
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 设置物料的属性“源”
	 * @param part
	 * @param attributeValue
	 * @param logInfo
	 * @throws WTException 
	 */
	private static void setSource( WTPart part , String attributeValue ) throws WTException {
		
		if( (attributeValue != null) && ( !attributeValue.trim().isEmpty() ) ){
			
			String partSource = CommonPDMUtil.getSourceEN( part );
			
			if( partSource != null && partSource.trim().equals( attributeValue.trim() ) ){
				return;
			}
			
			Source source = Source.toSource( attributeValue.trim() ) ;
			
			if( source != null ){

				part.setSource( source );
							
				PersistenceServerHelper.manager.update( part );
				//part= (WTPart)PersistenceHelper.manager.refresh(part);
				
			}
		}
	}
	
	/**
	 * 检入已检出的
	 * @param outPart
	 */
	private static void checkinWTPart( List<WTPart> outPart ){
		
		if( outPart != null ){
			for (int i = 0; i < outPart.size(); i++) {
				WTPart inPart = outPart.get( i );
				if( inPart != null ){
					try {
						CoreUtil.checkinObject(inPart, "物料属性更新完成");
					} catch (WTException e) {
						e.printStackTrace();
					}
				}
			}
		}		
	}
	
	/**
	 * 解析Excel配置表获取可以修改属性的内部名称
	 * @param string
	 * @return
	 */
	private static List<String> parseExcel( String string ) {
		List< String > list = new ArrayList<String>();
		
		if( string == null || string.trim().isEmpty() ){
			return list;
		}
		
		//获取第一个Sheet页
		Sheet sheet = ExcelUtil.getFirstSheet( string );
		
		if( sheet != null ){
			Iterator< Row > iterator =  sheet.rowIterator();
			
			//跳过表头
			if( iterator.hasNext() ){
				iterator.next();
			}
			
			while( iterator.hasNext() ){
				Row row = iterator.next();
				
				if( row != null ){
					//获取内部值
					String attributeName = ImportedExcelUtil.getCellValueAsString( row.getCell( 1 ) , true );
					
					if( attributeName != null && !attributeName.trim().isEmpty() ){
						list.add( attributeName.trim() );
					}				
				}
			}
		}
		
		return list;
	}

	/**
	 * 更新零部件名称属性
	 * @param part
	 * @param attributeValue
	 * @param logInfo
	 */
	public static void setName( WTPart part , String attributeValue ) {
		System.out.println("===start===》》》");
		if( ( attributeValue != null ) && ( !attributeValue.trim().isEmpty() ) ){
			
			String partName = part.getName();
			if( partName != null && partName.trim().equals( attributeValue.trim() ) ){
				return;
			}
			
			try {
				
				Identified identified = ( Identified )part.getMaster();
				WTPartMasterIdentity masteridentity = ( WTPartMasterIdentity )identified.getIdentificationObject();            
				masteridentity.setName( attributeValue );
				identified = IdentityHelper.service.changeIdentity( identified, masteridentity ); //更新名称
				//PersistenceServerHelper.manager.update( identified );				
				PersistenceHelper.manager.refresh(part);
			} catch (WTPropertyVetoException e) {				
				e.printStackTrace();
			} catch (WTException e) {
				e.printStackTrace();
			}
		}
	}

}
